package com.ltwc.lttv.fragment

import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.Fragment
import com.ltwc.lttv.activity.MainActivity
import com.ltwc.lttv.databinding.PlayerBinding
import com.ltwc.lttv.models.TVViewModel
import com.ltwc.lttv.net.LogUtil
import com.ltwc.callback.IPlayingCallback
import com.ltwc.video.TVVideoPlayer
import com.ltwc.view.CircularProgressBar
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.player.SystemPlayerManager
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import tv.danmaku.ijk.media.player.IjkMediaPlayer


class PlayerFragment : Fragment(), IPlayingCallback {

    private var _binding: PlayerBinding? = null
    private var playerView: TVVideoPlayer? = null
    private var tvViewModel: TVViewModel? = null
    private var loadingView: CircularProgressBar? = null
    private var loadFailed: View? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = PlayerBinding.inflate(inflater, container, false)
        playerView = _binding!!.newPlayView
        loadingView = _binding!!.loading
        loadFailed = _binding!!.loadFailed
        (playerView as ViewGroup).clearFocus()
        playerView!!.setIPlayingCallback(this)
        (activity as MainActivity).playerFragment = this
        (activity as MainActivity).getWindow()
            .addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        val exit = _binding!!.carwithClose
        /*exit.setOnClickListener{ _ ->
            (activity as MainActivity).back()
        }
        exit.setOnLongClickListener {
            // 处理长按事件
            (activity as MainActivity).showHelp()
            true // 返回 true 表示事件被消费，不会继续传递
        }*/
        (activity as MainActivity).fragmentReady()
        //中国移动机顶盒（安卓4.4系统）上的GSYVideoPlayer开发，坚定不移地使用 GSYVideoType.SURFACE
        //并且使用系统内核播放，为了安全起见，在安卓6.0以下的系统都使用系统内核播放，确实不会卡顿
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            GSYVideoType.setRenderType(GSYVideoType.SUFRACE);
            //将设置初始化放在这里
            PlayerFactory.setPlayManager(SystemPlayerManager::class.java)
        } else {
            GSYVideoType.setRenderType(GSYVideoType.GLSURFACE);
            //将设置初始化放在这里
            PlayerFactory.setPlayManager(IjkPlayerManager::class.java)
        }
        if ((activity as MainActivity).channelFull) {
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
        } else {
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
        }
        if ((activity as MainActivity).hardDecoding) {
            GSYVideoType.enableMediaCodec();//使用硬解码
            GSYVideoType.enableMediaCodecTexture()
        } else {
            GSYVideoType.disableMediaCodec();//关闭硬解码
            GSYVideoType.disableMediaCodecTexture()
        }
        //ijk关闭log
        IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT)
        return _binding!!.root
    }


    private var lastTime = 0L;
    private val handler = Handler()
    private val delay: Long = 100
    fun play(tvViewModel: TVViewModel) {
        this.tvViewModel = tvViewModel
        if (System.currentTimeMillis() - lastTime < 100) {
            keepRunnable()
        } else {
            playerView?.run {
                player(tvViewModel)
            }
        }
        lastTime = System.currentTimeMillis();
    }

    private fun player(tvViewModel: TVViewModel) {
        loadingView?.visibility = View.GONE
        loadFailed?.visibility = View.GONE
        loadingView?.reset()
        this.tvViewModel = tvViewModel
        val videoUrlCurrent = tvViewModel.getVideoUrlCurrent()
        playerView?.start(videoUrlCurrent, false, "")
    }

    fun keepRunnable() {
        handler.removeCallbacks(hideRunnable)
        handler.postDelayed(hideRunnable, delay)
    }

    private val hideRunnable = Runnable {
        try {
            playerView?.run {
                tvViewModel?.let { player(it) }
            }
        } catch (e: Exception) {
            LogUtil.e("播放出错了")
        }

    }


    fun changeMediaCodec() {
        if ((activity as MainActivity).hardDecoding) {
            GSYVideoType.enableMediaCodec();//使用硬解码
            GSYVideoType.enableMediaCodecTexture()
        } else {
            GSYVideoType.disableMediaCodec();//关闭硬解码
            GSYVideoType.disableMediaCodecTexture()
        }
        playerView?.startPlayLogic()
    }

    fun setAspectRatio(channelFull: Boolean) {
        if (channelFull) {
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);
        } else {
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9);
        }
        playerView?.startPlayLogic()
    }

    override fun onStart() {
        super.onStart()
        playerView?.startPlayLogic()
    }

    override fun onStop() {
        super.onStop()
        playerView?.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (playerView != null) {
            playerView!!.release()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        private const val TAG = "PlaybackVideoFragment"
    }

    override fun prepare() {
        LogUtil.e("prepare")
        loadingView?.visibility = View.VISIBLE
        loadingView?.setProgressX(2000, true)
    }

    override fun playing() {
        LogUtil.e("playing")
        loadingView?.reset()
        loadingView?.visibility = View.GONE
    }

    override fun error() {
        LogUtil.e("error")
        loadingView?.reset()
        //播放出错
        loadFailed?.visibility = View.VISIBLE
        loadingView?.visibility = View.GONE
    }

    override fun pause() {
        LogUtil.e("pause")
    }

    override fun playBufferingStart() {
        LogUtil.e("playBufferingStart")
        loadingView?.visibility = View.VISIBLE
        loadingView?.setProgressX(2000, true)
    }

    override fun playBufferingEnd() {
        LogUtil.e("playBufferingEnd")
        //缓冲结束
        loadingView?.reset()
        loadingView?.visibility = View.GONE
    }

    override fun setBufferingProgress(percent: Int) {
        LogUtil.e("setBufferingProgress=" + percent)
        loadingView?.progress = percent * 1.0f
    }
}
